package com.eureka.provider.controller;

import com.eureka.provider.pojo.Goods;
import com.eureka.provider.pojo.User;
import com.eureka.provider.service.IGoodsService;
import com.eureka.provider.service.IUserService;
import com.eureka.provider.vo.GoodsVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author sam
 * @since 2021-04-15
 */
@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {
    @Autowired
    IUserService userService;
    @Autowired
    IGoodsService goodsService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    ThymeleafViewResolver thymeleafViewResolver;

    @RequestMapping("/toList")
    @ResponseBody
    public List<GoodsVo> toList(User user){
        return goodsService.findGoodsVo();
    }

    /**
     * 页面缓存方式
     * @param model
     * @param user
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/toLoginPage",produces = "text/html;charset=utf-8")
    public String toList(Model model,
                         User user,
                         HttpServletRequest request,
                         HttpServletResponse response){
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String goodsList = (String) valueOperations.get("login");
        if(goodsList!=null){
            return goodsList;
        }
        model.addAttribute("user",user);
        model.addAttribute("goods",goodsService.findGoodsVo());
        //手动渲染并存入redis
        String html = thymeleafViewResolver.getTemplateEngine().process("login", new WebContext(
                request, response, request.getServletContext(), request.getLocale(), model.asMap()
        ));
        if(html!=null){
            valueOperations.set("login",html,20, TimeUnit.SECONDS);
            log.info("更新页面缓存");
        }
        return "login";
    }

    /**
     * 对象缓存方式
     * @param id
     * @return
     */
    @RequestMapping("/toDetail")
    @ResponseBody
    public GoodsVo toDetail(Long id){

        return goodsService.findGoodsVoById(id);
    }

}
